#include <ws2tcpip.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winsock2.h>
#include <stdint.h>
#include <windows.h>
#include <sqlite3.h>
#include <process.h>
#include <time.h>
#include <errno.h>
#include <ctype.h>
#include <direct.h>
#include "base64.h"

#pragma comment(lib, "ws2_32.lib")

#define PORT 65432
#define BUFFER_SIZE 5120
#define MAX_CLIENTS 100

// 消息类型定义
#define MSG_TYPE_TEXT 0x01
#define MSG_TYPE_FILE 0x02
#define MSG_TYPE_LOGIN 0x03
#define MSG_TYPE_REGISTER 0x04
#define MSG_TYPE_RESPONSE 0x05
#define MSG_TYPE_PRIVATE_TEXT 0x06
#define MSG_TYPE_FILE_SEND_REQUEST 0x07
#define MSG_TYPE_FILE_RECEIVE_NOTICE 0x08

// 客户端信息结构体
typedef struct {
    SOCKET socket;
    wchar_t username[256];
    BOOL logged_in; // 新增：表示客户端是否登录成功
} ClientInfo;

// 全局变量
HWND hChatList;
CRITICAL_SECTION clients_cs;
SOCKET server_fd;
HFONT hFont;
ClientInfo* clients[MAX_CLIENTS];
int client_count = 0;
float SERVER_EDITION = 1.2;

// 保存文本消息到 D:\TCP\received_data.txt 文件中
void save_text_to_file(const unsigned char *data, int length) {
    FILE *fp = fopen("D:\\TCP\\received_data.txt", "ab"); // 使用追加模式
    if (fp != NULL) {
        // 写入数据
        fwrite(data, 1, length, fp);
        // 写入换行符
        fputc('\n', fp);
        fclose(fp);
        printf("Text message saved to D:\\TCP\\received_data.txt\n");
    } else {
        perror("Failed to open file D:\\TCP\\received_data.txt\n");
    }
}

// 保存文本数据到 SQLite 数据库
void save_text_to_database(const unsigned char *data, int length) {
    sqlite3 *db;
    char *zErrMsg = 0;
    int rc;
    sqlite3_stmt *stmt;

    rc = sqlite3_open("D:\\TCP\\data.db", &db);
    if (rc) {
        fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
        return;
    }

    // 创建表
    const char *create_table_sql = "CREATE TABLE IF NOT EXISTS messages (id INTEGER PRIMARY KEY AUTOINCREMENT, message TEXT, timestamp DATETIME DEFAULT CURRENT_TIMESTAMP);";
    rc = sqlite3_exec(db, create_table_sql, 0, 0, &zErrMsg);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "SQL error: %s\n", zErrMsg);
        sqlite3_free(zErrMsg);
    }

    // 准备插入语句
    const char *insert_sql = "INSERT INTO messages (message) VALUES (?);";
    rc = sqlite3_prepare_v2(db, insert_sql, -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
        sqlite3_close(db);
        return;
    }

    // 绑定数据
    rc = sqlite3_bind_text(stmt, 1, (const char *)data, length, SQLITE_STATIC);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
        sqlite3_finalize(stmt);
        sqlite3_close(db);
        return;
    }

    // 执行插入语句
    rc = sqlite3_step(stmt);
    if (rc != SQLITE_DONE) {
        fprintf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
    }

    // 释放资源
    sqlite3_finalize(stmt);
    sqlite3_close(db);
    printf("Text message saved to database\n");
}

// 登录请求处理
void handle_login_request(ClientInfo* client_info, const char* login_msg) {
    char encoded_username[256];
    char encoded_password[256];
    sscanf(login_msg, "%[^:]:%s", encoded_username, encoded_password);

    // 解码Base64编码的账号
    int decoded_username_length;
    unsigned char* decoded_username = Base64Decode(encoded_username, strlen(encoded_username), &decoded_username_length);
    if (decoded_username == NULL) {
        // 处理解码失败
        const char* response = "登录失败，账号数据解码错误";
        char msg_with_type[BUFFER_SIZE + 2];
        msg_with_type[0] = MSG_TYPE_RESPONSE;
        strcpy(msg_with_type + 1, response);
        int total_length = 1 + strlen(response);

        int encoded_len;
        char* encoded_response = Base64Encode((const unsigned char *)msg_with_type, total_length, &encoded_len);
        if (encoded_response != NULL) {
            send(client_info->socket, encoded_response, encoded_len, 0);
            free(encoded_response);
        }
        return;
    }

    // 解码Base64编码的密码
    int decoded_password_length;
    unsigned char* decoded_password = Base64Decode(encoded_password, strlen(encoded_password), &decoded_password_length);
    if (decoded_password == NULL) {
        // 处理解码失败
        const char* response = "登录失败，密码数据解码错误";
        char msg_with_type[BUFFER_SIZE + 2];
        msg_with_type[0] = MSG_TYPE_RESPONSE;
        strcpy(msg_with_type + 1, response);
        int total_length = 1 + strlen(response);

        int encoded_len;
        char* encoded_response = Base64Encode((const unsigned char *)msg_with_type, total_length, &encoded_len);
        if (encoded_response != NULL) {
            send(client_info->socket, encoded_response, encoded_len, 0);
            free(encoded_response);
        }
        free(decoded_username);
        return;
    }

    // 将解码后的账号和密码转换为字符串
    char decoded_username_str[BUFFER_SIZE];
    memcpy(decoded_username_str, decoded_username, decoded_username_length);
    decoded_username_str[decoded_username_length] = '\0';

    char decoded_password_str[BUFFER_SIZE];
    memcpy(decoded_password_str, decoded_password, decoded_password_length);
    decoded_password_str[decoded_password_length] = '\0';

    // 检查该账号是否已经登录
    for (int i = 0; i < client_count; i++) {
        if (clients[i]->logged_in) {
            wchar_t existing_username[256];
            MultiByteToWideChar(CP_UTF8, 0, decoded_username_str, -1, existing_username, sizeof(existing_username) / sizeof(wchar_t));
            if (wcscmp(clients[i]->username, existing_username) == 0) {
                const char* response = "该用户已登录";
                char msg_with_type[BUFFER_SIZE + 2];
                msg_with_type[0] = MSG_TYPE_RESPONSE;
                strcpy(msg_with_type + 1, response);
                int total_length = 1 + strlen(response);
                int encoded_len;
                char* encoded_response = Base64Encode((const unsigned char *)msg_with_type, total_length, &encoded_len);
                if (encoded_response != NULL) {
                    send(client_info->socket, encoded_response, encoded_len, 0);
                    free(encoded_response);
                }
                free(decoded_username);
                free(decoded_password);
                return;
            }
        }
    }

    // 读取注册文件，验证账号密码
    FILE* file = fopen("D:\\TCP\\users.txt", "r");
    if (file != NULL) {
        char line[BUFFER_SIZE];
        while (fgets(line, sizeof(line), file) != NULL) {
            char stored_username[256];
            char stored_password[256];
            sscanf(line, "%[^:]:%s", stored_username, stored_password);
            if (strcmp(decoded_username_str, stored_username) == 0 && strcmp(decoded_password_str, stored_password) == 0) {
                // 登录成功
                const char* response = "登录成功";
                char msg_with_type[BUFFER_SIZE + 2];
                msg_with_type[0] = MSG_TYPE_RESPONSE;
                strcpy(msg_with_type + 1, response);
                int total_length = 1 + strlen(response);

                int encoded_len;
                char* encoded_response = Base64Encode((const unsigned char *)msg_with_type, total_length, &encoded_len);
                if (encoded_response != NULL) {
                    send(client_info->socket, encoded_response, encoded_len, 0);
                    free(encoded_response);
                }

                // 更新客户端登录信息
                client_info->logged_in = TRUE;
                MultiByteToWideChar(CP_UTF8, 0, decoded_username_str, -1, client_info->username, sizeof(client_info->username) / sizeof(wchar_t));

                // 在服务端界面显示登录成功提示
                wchar_t display_msg[BUFFER_SIZE];
                swprintf(display_msg, L"%ls 登录成功", client_info->username);
                EnterCriticalSection(&clients_cs);
                SendMessageW(hChatList, LB_ADDSTRING, 0, (LPARAM)display_msg);
                LeaveCriticalSection(&clients_cs);

                fclose(file);
                free(decoded_username);
                free(decoded_password);
                return;
            }
        }
        fclose(file);
    }

    // 登录失败
    const char* response = "登录失败";
    char msg_with_type[BUFFER_SIZE + 2];
    msg_with_type[0] = MSG_TYPE_RESPONSE;
    strcpy(msg_with_type + 1, response);
    int total_length = 1 + strlen(response);

    int encoded_len;
    char* encoded_response = Base64Encode((const unsigned char *)msg_with_type, total_length, &encoded_len);
    if (encoded_response != NULL) {
        send(client_info->socket, encoded_response, encoded_len, 0);
        free(encoded_response);
    }

    // 在服务端界面显示登录失败提示
    wchar_t w_username[256];
    MultiByteToWideChar(CP_UTF8, 0, decoded_username_str, -1, w_username, sizeof(w_username) / sizeof(wchar_t));
    wchar_t display_msg[BUFFER_SIZE];
    swprintf(display_msg, L"%ls 登录失败", w_username);
    EnterCriticalSection(&clients_cs);
    SendMessageW(hChatList, LB_ADDSTRING, 0, (LPARAM)display_msg);
    LeaveCriticalSection(&clients_cs);

    free(decoded_username);
    free(decoded_password);
}

// 注册请求处理
void handle_register_request(ClientInfo* client_info, const char* register_msg) {
    char encoded_username[256];
    char encoded_password[256];
    sscanf(register_msg, "%[^:]:%s", encoded_username, encoded_password);

    // 解码Base64编码的账号
    int decoded_username_length;
    unsigned char* decoded_username = Base64Decode(encoded_username, strlen(encoded_username), &decoded_username_length);
    if (decoded_username == NULL) {
        // 处理解码失败
        const char* response = "注册失败，账号数据解码错误";
        char msg_with_type[BUFFER_SIZE + 2];
        msg_with_type[0] = MSG_TYPE_RESPONSE;
        strcpy(msg_with_type + 1, response);
        int total_length = 1 + strlen(response);

        int encoded_len;
        char* encoded_response = Base64Encode((const unsigned char *)msg_with_type, total_length, &encoded_len);
        if (encoded_response != NULL) {
            send(client_info->socket, encoded_response, encoded_len, 0);
            free(encoded_response);
        }

        // 在服务端界面显示注册失败提示
        wchar_t display_msg[BUFFER_SIZE];
        swprintf(display_msg, L"未知账号 注册失败，账号数据解码错误");
        EnterCriticalSection(&clients_cs);
        SendMessageW(hChatList, LB_ADDSTRING, 0, (LPARAM)display_msg);
        LeaveCriticalSection(&clients_cs);

        return;
    }

    // 解码Base64编码的密码
    int decoded_password_length;
    unsigned char* decoded_password = Base64Decode(encoded_password, strlen(encoded_password), &decoded_password_length);
    if (decoded_password == NULL) {
        // 处理解码失败
        const char* response = "注册失败，密码数据解码错误";
        char msg_with_type[BUFFER_SIZE + 2];
        msg_with_type[0] = MSG_TYPE_RESPONSE;
        strcpy(msg_with_type + 1, response);
        int total_length = 1 + strlen(response);

        int encoded_len;
        char* encoded_response = Base64Encode((const unsigned char *)msg_with_type, total_length, &encoded_len);
        if (encoded_response != NULL) {
            send(client_info->socket, encoded_response, encoded_len, 0);
            free(encoded_response);
        }

        // 在服务端界面显示注册失败提示
        wchar_t w_username[256];
        MultiByteToWideChar(CP_UTF8, 0, (const char*)decoded_username, -1, w_username, sizeof(w_username) / sizeof(wchar_t));
        wchar_t display_msg[BUFFER_SIZE];
        swprintf(display_msg, L"%ls 注册失败，密码数据解码错误", w_username);
        EnterCriticalSection(&clients_cs);
        SendMessageW(hChatList, LB_ADDSTRING, 0, (LPARAM)display_msg);
        LeaveCriticalSection(&clients_cs);

        free(decoded_username);
        return;
    }

    // 将解码后的账号和密码转换为字符串
    char decoded_username_str[BUFFER_SIZE];
    memcpy(decoded_username_str, decoded_username, decoded_username_length);
    decoded_username_str[decoded_username_length] = '\0';

    char decoded_password_str[BUFFER_SIZE];
    memcpy(decoded_password_str, decoded_password, decoded_password_length);
    decoded_password_str[decoded_password_length] = '\0';

    // 检查账号是否已存在
    FILE* file = fopen("D:\\TCP\\users.txt", "r");
    if (file != NULL) {
        char line[BUFFER_SIZE];
        while (fgets(line, sizeof(line), file) != NULL) {
            char stored_username[256];
            sscanf(line, "%[^:]:", stored_username);
            if (strcmp(decoded_username_str, stored_username) == 0) {
                // 账号已存在
                const char* response = "注册失败，账号已存在";
                char msg_with_type[BUFFER_SIZE + 2];
                msg_with_type[0] = MSG_TYPE_RESPONSE;
                strcpy(msg_with_type + 1, response);
                int total_length = 1 + strlen(response);

                int encoded_len;
                char* encoded_response = Base64Encode((const unsigned char *)msg_with_type, total_length, &encoded_len);
                if (encoded_response != NULL) {
                    send(client_info->socket, encoded_response, encoded_len, 0);
                    free(encoded_response);
                }

                // 在服务端界面显示注册失败提示
                wchar_t w_username[256];
                MultiByteToWideChar(CP_UTF8, 0, decoded_username_str, -1, w_username, sizeof(w_username) / sizeof(wchar_t));
                wchar_t display_msg[BUFFER_SIZE];
                swprintf(display_msg, L"%ls 注册失败，账号已存在", w_username);
                EnterCriticalSection(&clients_cs);
                SendMessageW(hChatList, LB_ADDSTRING, 0, (LPARAM)display_msg);
                LeaveCriticalSection(&clients_cs);

                fclose(file);
                free(decoded_username);
                free(decoded_password);
                return;
            }
        }
        fclose(file);
    }

    // 保存账号密码
    file = fopen("D:\\TCP\\users.txt", "a");
    if (file != NULL) {
        fprintf(file, "%s:%s\n", decoded_username_str, decoded_password_str);
        fclose(file);
        // 注册成功
        const char* response = "注册成功";
        char msg_with_type[BUFFER_SIZE + 2];
        msg_with_type[0] = MSG_TYPE_RESPONSE;
        strcpy(msg_with_type + 1, response);
        int total_length = 1 + strlen(response);

        int encoded_len;
        char* encoded_response = Base64Encode((const unsigned char *)msg_with_type, total_length, &encoded_len);
        if (encoded_response != NULL) {
            send(client_info->socket, encoded_response, encoded_len, 0);
            free(encoded_response);
        }

        // 在服务端界面显示注册成功提示
        wchar_t w_username[256];
        MultiByteToWideChar(CP_UTF8, 0, decoded_username_str, -1, w_username, sizeof(w_username) / sizeof(wchar_t));
        wchar_t display_msg[BUFFER_SIZE];
        swprintf(display_msg, L"%ls 注册成功", w_username);
        EnterCriticalSection(&clients_cs);
        SendMessageW(hChatList, LB_ADDSTRING, 0, (LPARAM)display_msg);
        LeaveCriticalSection(&clients_cs);
    }

    free(decoded_username);
    free(decoded_password);
}

// 客户端处理线程
unsigned __stdcall handle_client(void* arg) {
    ClientInfo* client_info = (ClientInfo*)arg;
    SOCKET client_socket = client_info->socket;
    char buffer[BUFFER_SIZE] = {0};
    int bytes_received;
    int decoded_length;
    unsigned char *decoded_data;
    unsigned char msg_type;
    unsigned char *actual_data;
    int actual_length;
    int wlen;
    wchar_t* wbuffer;
    wchar_t display_msg[BUFFER_SIZE];
    char *response;
    int encoded_len;
    char *encoded_response;

    // 设置套接字为非阻塞模式
    unsigned long mode = 1;
    if (ioctlsocket(client_socket, FIONBIO, &mode) == SOCKET_ERROR) {
        printf("ioctlsocket failed\n");
        closesocket(client_socket);
        free(client_info);
        // 从客户端列表中移除该客户端信息
        for (int i = 0; i < client_count; i++) {
            if (clients[i] == client_info) {
                for (int j = i; j < client_count - 1; j++) {
                    clients[j] = clients[j + 1];
                }
                client_count--;
                break;
            }
        }
        return 0;
    }

    while (1) {
        bytes_received = recv(client_socket, buffer, BUFFER_SIZE, 0);
        if (bytes_received == SOCKET_ERROR) {
            if (WSAGetLastError() == WSAEWOULDBLOCK) {
                // 没有数据到达，继续循环
                Sleep(10);
                continue;
            } else {
                printf("Client disconnected\n");
                break;
            }
        } else if (bytes_received == 0) {
            printf("Client disconnected\n");
            break;
        }

        // Base64解码
        decoded_data = Base64Decode(buffer, bytes_received, &decoded_length);
        if (decoded_data != NULL) {
            if (decoded_length > 0) {
                msg_type = decoded_data[0];
                uint32_t received_crc;
                memcpy(&received_crc, decoded_data + 1, sizeof(uint32_t));
                actual_data = decoded_data + 1 + sizeof(uint32_t);
                actual_length = decoded_length - 1 - sizeof(uint32_t);

                // 计算接收到数据的CRC32校验值
                uint32_t calculated_crc = crc32(actual_data, actual_length);

                // 注释掉CRC32校验失败的处理代码
                // if (received_crc != calculated_crc) {
                //     printf("CRC32校验失败\n");
                //     // 可以选择发送错误响应给客户端
                //     response = "CRC32校验失败";
                //     char msg_with_type[BUFFER_SIZE + 2];
                //     msg_with_type[0] = MSG_TYPE_RESPONSE;
                //     strcpy(msg_with_type + 1, response);
                //     int total_length = 1 + strlen(response);

                //     encoded_len;
                //     encoded_response = Base64Encode((const unsigned char *)msg_with_type, total_length, &encoded_len);

                //     if (encoded_response != NULL) {
                //         send(client_socket, encoded_response, encoded_len, 0);
                //         free(encoded_response);
                //     }
                //     free(decoded_data);
                //     continue;
                // }

                switch (msg_type) {
                    case MSG_TYPE_LOGIN: {
                        char login_msg[BUFFER_SIZE];
                        memcpy(login_msg, actual_data, actual_length);
                        login_msg[actual_length] = '\0';
                        handle_login_request(client_info, login_msg);
                        break;
                    }
                    case MSG_TYPE_REGISTER: {
                        char register_msg[BUFFER_SIZE];
                        memcpy(register_msg, actual_data, actual_length);
                        register_msg[actual_length] = '\0';
                        handle_register_request(client_info, register_msg);
                        break;
                    }
                    case MSG_TYPE_TEXT:
                        // 去除多余的空字符
                        while (actual_length > 0 && actual_data[actual_length - 1] == '\0') {
                            actual_length--;
                        }

                        // 转换UTF-8数据为宽字符
                        wlen = MultiByteToWideChar(CP_UTF8, 0, (const char*)actual_data, actual_length, NULL, 0);
                        wbuffer = (wchar_t*)malloc((wlen + 1) * sizeof(wchar_t));

                        MultiByteToWideChar(CP_UTF8, 0, (const char*)actual_data, actual_length, wbuffer, wlen);
                        wbuffer[wlen] = L'\0'; // 添加字符串结束符

                        // 打印到控制台（调试用）
                        wprintf(L"Received text: %ls\n", wbuffer);

                        // 保存到文件
                        save_text_to_file(actual_data, actual_length);
                        
                        // 保存到数据库
                        save_text_to_database(actual_data, actual_length);

                        // 显示接收到的文本消息到UI
                        if (client_info->logged_in) {
                            swprintf(display_msg, L"%ls: %ls", client_info->username, wbuffer);
                        } else {
                            swprintf(display_msg, L"客户端: %ls", wbuffer);
                        }
                        EnterCriticalSection(&clients_cs);
                        SendMessageW(hChatList, LB_ADDSTRING, 0, (LPARAM)display_msg);
                        LeaveCriticalSection(&clients_cs);

                        // 广播消息给所有已登录的客户端
                        if (client_info->logged_in) {
                            char broadcast_msg[BUFFER_SIZE];
                            sprintf(broadcast_msg, "%ls: %.*s", client_info->username, actual_length, (const char*)actual_data);
                            char msg_with_type[BUFFER_SIZE + 2];

                            msg_with_type[0] = MSG_TYPE_TEXT;
                            strcpy(msg_with_type + 1, broadcast_msg);
                            int total_length = 1 + strlen(broadcast_msg);

                            int encoded_len;
                            char* encoded_response = Base64Encode((const unsigned char *)msg_with_type, total_length, &encoded_len);
                            if (encoded_response != NULL) {
                                for (int i = 0; i < client_count; i++) {
                                    if (clients[i]->logged_in && clients[i]->socket != client_socket) {
                                        send(clients[i]->socket, encoded_response, encoded_len, 0);
                                    }
                                }
                                free(encoded_response);
                            }
                        }

                        free(wbuffer);
                        break;
                    case MSG_TYPE_PRIVATE_TEXT: {
                        char private_msg[BUFFER_SIZE];
                        memcpy(private_msg, actual_data, actual_length);
                        private_msg[actual_length] = '\0';

                        char *equal_pos = strchr(private_msg, '=');
                        if (equal_pos != NULL) {
                            *equal_pos = '\0';
                            char target_username[256];
                            strcpy(target_username, private_msg + 1); // 去掉开头的 '/'

                            char *content = equal_pos + 1;

                            // 找到目标客户端
                            for (int i = 0; i < client_count; i++) {
                                if (clients[i]->logged_in) {
                                    char existing_username[256];
                                    WideCharToMultiByte(CP_UTF8, 0, clients[i]->username, -1, existing_username, sizeof(existing_username), NULL, NULL);
                                    if (strcmp(existing_username, target_username) == 0) {
                                        // 构建私聊消息
                                        char broadcast_msg[BUFFER_SIZE];
                                        char sender_username[256];
                                        WideCharToMultiByte(CP_UTF8, 0, client_info->username, -1, sender_username, sizeof(sender_username), NULL, NULL);
                                        sprintf(broadcast_msg, "[私聊] %s: %s", sender_username, content);

                                        char msg_with_type[BUFFER_SIZE + 2];
                                        msg_with_type[0] = MSG_TYPE_PRIVATE_TEXT;
                                        strcpy(msg_with_type + 1, broadcast_msg);
                                        int total_length = 1 + strlen(broadcast_msg);

                                        int encoded_len;
                                        char* encoded_response = Base64Encode((const unsigned char *)msg_with_type, total_length, &encoded_len);

                                        if (encoded_response != NULL) {
                                            send(clients[i]->socket, encoded_response, encoded_len, 0);
                                            free(encoded_response);
                                        }

                                        // 在服务端界面显示私聊消息
                                        wchar_t w_sender_username[256];
                                        wchar_t w_target_username[256];
                                        wchar_t w_content[BUFFER_SIZE];
                                        MultiByteToWideChar(CP_UTF8, 0, sender_username, -1, w_sender_username, sizeof(w_sender_username) / sizeof(wchar_t));
                                        MultiByteToWideChar(CP_UTF8, 0, target_username, -1, w_target_username, sizeof(w_target_username) / sizeof(wchar_t));
                                        MultiByteToWideChar(CP_UTF8, 0, content, -1, w_content, sizeof(w_content) / sizeof(wchar_t));

                                        wchar_t display_msg[BUFFER_SIZE];
                                        swprintf(display_msg, L"[私聊] %ls -> %ls: %ls", w_sender_username, w_target_username, w_content);
                                        EnterCriticalSection(&clients_cs);
                                        SendMessageW(hChatList, LB_ADDSTRING, 0, (LPARAM)display_msg);
                                        LeaveCriticalSection(&clients_cs);

                                        // 保存私聊消息到数据库
                                        save_text_to_database((const unsigned char *)broadcast_msg, strlen(broadcast_msg));

                                        break;
                                    }
                                }
                            }
                        }
                        break;
                    }
                    case MSG_TYPE_FILE: {
                        char target_username[256];
                        char file_name[256];
                        char *file_data = strchr((char *)actual_data, ':');
                        if (file_data != NULL) {
                            *file_data = '\0';
                            strcpy(target_username, (char *)actual_data);
                            file_data++;

                            char *file_name_start = strchr(file_data, ':');
                            if (file_name_start != NULL) {
                                *file_name_start = '\0';
                                strcpy(file_name, file_data);
                                file_data = file_name_start + 1;
                            }

                            int file_size = actual_length - (strlen(target_username) + 1 + strlen(file_name) + 1);

                            // 保存文件到 D:\TCP 目录下
                            char file_path[260];
                            time_t t = time(NULL);
                            struct tm tm = *localtime(&t);

                            sprintf(file_path, "D:\\TCP\\%ls_%d%d%d%02d%02d%02d_%s", client_info->username, tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, file_name);
                            FILE *fp = fopen(file_path, "wb");

                            if (fp != NULL) {
                                fwrite(file_data, 1, file_size, fp);
                                fclose(fp);
                                printf("File saved to %s\n", file_path);
                            } else {
                                perror("Failed to open file for writing");
                            }

                            // 找到目标客户端
                            BOOL target_found = FALSE;
                            for (int i = 0; i < client_count; i++) {
                                if (clients[i]->logged_in) {
                                    char existing_username[256];
                                    WideCharToMultiByte(CP_UTF8, 0, clients[i]->username, -1, existing_username, sizeof(existing_username), NULL, NULL);
                                    if (strcmp(existing_username, target_username) == 0) {
                                        // 构建文件消息
                                        char broadcast_msg[BUFFER_SIZE];
                                        char sender_username[256];
                                        WideCharToMultiByte(CP_UTF8, 0, client_info->username, -1, sender_username, sizeof(sender_username), NULL, NULL);

                                        sprintf(broadcast_msg, "[文件] %s: 收到来自 %s 的文件，请查收", target_username, sender_username);

                                        char msg_with_type[BUFFER_SIZE + 2];

                                        msg_with_type[0] = MSG_TYPE_FILE;
                                        strcpy(msg_with_type + 1, broadcast_msg);
                                        int total_length = 1 + strlen(broadcast_msg);

                                        int encoded_len;
                                        char *encoded_response = Base64Encode((const unsigned char *)msg_with_type, total_length, &encoded_len);
                                        if (encoded_response != NULL) {
                                            send(clients[i]->socket, encoded_response, encoded_len, 0);
                                            free(encoded_response);
                                        }

                                        // 保存文件到接收方目录下
                                        wchar_t receiver_folder[260];
                                        swprintf(receiver_folder, L"D:\\%ls", clients[i]->username);
                                        char receiver_file_path[260];
                                        sprintf(receiver_file_path, "%ls\\%ls_%d%d%d%02d%02d%02d_%s", receiver_folder, client_info->username, tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, file_name);
                                        FILE *fp_receiver = fopen(receiver_file_path, "wb");

                                        if (fp_receiver != NULL) {
                                            fwrite(file_data, 1, file_size, fp_receiver);
                                            fclose(fp_receiver);
                                            printf("File saved to %s\n", receiver_file_path);
                                        } else {
                                            perror("Failed to open file for writing");
                                        }

                                        target_found = TRUE;
                                        break;
                                    }
                                }
                            }

                            // 在服务端界面显示文件发送成功消息
                            wchar_t server_display_msg[BUFFER_SIZE];
                            if (target_found) {
                                // 转换目标用户名到宽字符
                                int wlen = MultiByteToWideChar(CP_UTF8, 0, target_username, -1, NULL, 0);
                                wchar_t *w_target_username = (wchar_t *)malloc((wlen + 1) * sizeof(wchar_t));
                                MultiByteToWideChar(CP_UTF8, 0, target_username, -1, w_target_username, wlen);
                                w_target_username[wlen] = L'\0';

                                swprintf(server_display_msg, L"%ls成功向%ls发送文件", client_info->username, w_target_username);
                                free(w_target_username);
                            } else {
                                swprintf(server_display_msg, L"%ls尝试向不存在的用户发送文件", client_info->username);
                            }

                            EnterCriticalSection(&clients_cs);
                            SendMessageW(hChatList, LB_ADDSTRING, 0, (LPARAM)server_display_msg);
                            LeaveCriticalSection(&clients_cs);
                        }
                        break;
                    }
                }
            }

            free(decoded_data);

            // 向客户端发送响应
            response = "Message received";
            char msg_with_type[BUFFER_SIZE + 2];
            msg_with_type[0] = MSG_TYPE_RESPONSE;
            strcpy(msg_with_type + 1, response);
            int total_length = 1 + strlen(response);

            encoded_len;
            encoded_response = Base64Encode((const unsigned char *)msg_with_type, total_length, &encoded_len);

            if (encoded_response != NULL) {
                send(client_socket, encoded_response, encoded_len, 0);
                free(encoded_response);
            }
        } else {
            printf("Base64 decoding failed\n");
        }

        // 清空接收缓冲区
        memset(buffer, 0, BUFFER_SIZE);
    }

    // 当客户端断开连接时，检查是否登录并显示退出信息
    if (client_info->logged_in) {
        wchar_t display_msg[BUFFER_SIZE];
        swprintf(display_msg, L"%ls 退出登录", client_info->username);
        EnterCriticalSection(&clients_cs);
        SendMessageW(hChatList, LB_ADDSTRING, 0, (LPARAM)display_msg);
        LeaveCriticalSection(&clients_cs);
    }

    // 关闭客户端套接字
    closesocket(client_socket);
    free(client_info);
    // 从客户端列表中移除该客户端信息
    for (int i = 0; i < client_count; i++) {
        if (clients[i] == client_info) {
            for (int j = i; j < client_count - 1; j++) {
                clients[j] = clients[j + 1];
            }
            client_count--;
            break;
        }
    }
    printf("Client thread exiting\n");
    return 0;
}

// 接受客户端连接的线程
unsigned __stdcall accept_clients(void* arg) {
    while (1) {
        SOCKET client_socket = accept(server_fd, NULL, NULL);
        if (client_socket == INVALID_SOCKET) {
            printf("accept failed\n");
            continue;
        }

        // 创建新线程处理客户端连接
        ClientInfo* client_info = (ClientInfo*)malloc(sizeof(ClientInfo));
        client_info->socket = client_socket;
        memset(client_info->username, 0, sizeof(client_info->username));
        client_info->logged_in = FALSE; // 初始化登录状态为未登录

        // 将新客户端信息添加到客户端列表中
        if (client_count < MAX_CLIENTS) {
            clients[client_count++] = client_info;
        }

        // 发送服务端版本信息
        send(client_socket, (const char*)&SERVER_EDITION, sizeof(SERVER_EDITION), 0);

        HANDLE thread_handle = (HANDLE)_beginthreadex(NULL, 0, handle_client, (void*)client_info, 0, NULL);

        if (thread_handle == 0) {
            printf("CreateThread failed\n");
            free(client_info);
            closesocket(client_socket);
            continue;
        }

        // 关闭线程句柄并释放资源
        CloseHandle(thread_handle);
    }
    return 0;
}

// 窗口过程
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
    switch (message) {
    case WM_CREATE:
        InitializeCriticalSection(&clients_cs);

        hFont = CreateFontW(14, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_SWISS, L"宋体");

        hChatList = CreateWindowW(L"LISTBOX", L"",
            WS_CHILD | WS_VISIBLE | WS_VSCROLL | LBS_NOINTEGRALHEIGHT,
            10, 10, 600, 280, hWnd, (HMENU)1001, NULL, NULL);
        SendMessageW(hChatList, WM_SETFONT, (WPARAM)hFont, TRUE);
        break;
    case WM_DESTROY:
        DeleteCriticalSection(&clients_cs);
        closesocket(server_fd);
        WSACleanup();
        DeleteObject(hFont);
        PostQuitMessage(0);
        break;
    default:
        return DefWindowProcW(hWnd, message, wParam, lParam);
    }
    return 0;
}

// WinMain 函数
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
    // 初始化 Winsock
    WSADATA wsaData;
    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
        printf("WSAStartup failed\n");
        return -1;
    }

    // 初始化互斥锁
    InitializeCriticalSection(&clients_cs);

    // 创建文件目录
    _wmkdir(L"D:\\TCP");

    // 创建套接字
    server_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (server_fd == INVALID_SOCKET) {
        printf("socket failed\n");
        WSACleanup();
        return -1;
    }

    int opt = 1;
    if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&opt, sizeof(opt))) {
        perror("setsockopt");
        closesocket(server_fd);
        WSACleanup();
        return -1;
    }

    struct sockaddr_in address;
    address.sin_family = AF_INET;
    // 指定 IP 地址为 127.0.0.1
    address.sin_addr.s_addr = inet_addr("127.0.0.1");
    address.sin_port = htons(PORT);

    if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) == SOCKET_ERROR) {
        printf("bind failed\n");
        closesocket(server_fd);
        WSACleanup();
        return -1;
    }

    if (listen(server_fd, 3) == SOCKET_ERROR) {
        printf("listen failed\n");
        closesocket(server_fd);
        WSACleanup();
        return -1;
    }

    printf("Server listening on IP: %s, Port: %d...\n", inet_ntoa(address.sin_addr), ntohs(address.sin_port));

    // 注册服务器窗口类
    WNDCLASSEXW wc = {0};
    wc.cbSize = sizeof(WNDCLASSEXW);
    wc.lpfnWndProc = WndProc;
    wc.hInstance = hInstance;
    wc.lpszClassName = L"TCPServerWindowClass";
    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
    wc.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_ARROW));
    RegisterClassExW(&wc);

    // 创建服务器窗口
    HWND hWnd = CreateWindowExW(
        0, L"TCPServerWindowClass", L"Win32 TCP Server",
        WS_OVERLAPPEDWINDOW,
        CW_USEDEFAULT, CW_USEDEFAULT, 640, 380,
        NULL, NULL, hInstance, NULL
    );

    if (hWnd == NULL) {
        printf("Window creation failed\n");
        closesocket(server_fd);
        WSACleanup();
        return -1;
    }

    // 创建接受客户端连接的线程
    _beginthreadex(NULL, 0, accept_clients, NULL, 0, NULL);

    ShowWindow(hWnd, nCmdShow);
    UpdateWindow(hWnd);

    MSG msg;
    while (GetMessageW(&msg, NULL, 0, 0)) {
        TranslateMessage(&msg);
        DispatchMessageW(&msg);
    }

    return 0;
}